package cn.com.easyfelling.utils;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;

public class DBUtilsBindThread {

  public static final ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

  public static Connection getConnection() {
    try {
      Connection connection = threadLocal.get();
      if(connection != null){
        return connection;
      }
      // 1.配置4个基本要素
      String url = "jdbc:mysql://120.79.55.11:3306/easyfeeling?serverTimezone=Asia/Shanghai";
      String user = "easyfeeling";
      String password = "iJ5CwzCGPmwPwMPN";
      String driverName = "com.mysql.cj.jdbc.Driver";
      // 通过反射实例化Driver，可省略
      Driver driver = (Driver)Class.forName(driverName).getConstructor().newInstance();
      // 注册驱动，可省略
      DriverManager.registerDriver(driver);
      Connection cc = DriverManager.getConnection(url, user, password);
      threadLocal.set(cc);
      return cc;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * 关闭资源
   * @param connection
   * @param statement
   * @param resultSet
   */
  public static void closeAll(Connection connection, Statement statement, ResultSet resultSet){

    try {
      if (resultSet != null) {
        resultSet.close();
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }

    try {
      if (statement != null) {
        statement.close();
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
    try {
      if (connection != null) {
        connection.close();
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }

  }

}

